package models

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"token-for-token/global"
)

type ChainConfig struct {
	Id              primitive.ObjectID `bson:"_id ,omitempty"`
	ChainName       string             `bson:"chainName"`
	ChainId         int64              `bson:"chainId"`
	RpcUrl          string             `bson:"rpcUrl"`
	LastBlockNumber int64              `bson:"lastBlockNumber"`
}

func (c *ChainConfig) GetChainInfoForId(id string) error {
	config := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_config")
	// 将字符串ID转换为ObjectID
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return err
	}
	filter := bson.M{"_id": objID}
	err = config.FindOne(context.Background(), filter).Decode(&c)
	return err
}

// 根据rpcUrl判断是否存在
func (c *ChainConfig) GetChainInfoForRpcUrl(rpcUrl string) error {
	config := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_config")
	filter := bson.M{"rpcUrl": rpcUrl}
	err := config.FindOne(context.Background(), filter).Decode(&c)
	return err
}

// 根据rpcUrl更新lastBlockNumber
func (c *ChainConfig) UpdateChainConfigLastBlockNumber(lastBlockNumber int64) error {
	config := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_config")
	filter := bson.M{"rpcUrl": c.RpcUrl}
	update := bson.M{"$set": bson.M{"lastBlockNumber": lastBlockNumber}}
	_, err := config.UpdateOne(context.Background(), filter, update)
	return err
}
